import React, {Component} from 'react'
import {View, Text, TouchableOpacity, ScrollView, StyleSheet, Image, Button} from 'react-native'
import {GetChapterApi} from '../../config/api'
import Loading from '../common/loading_common'
import SentenceLabel from './sentence_label'
import Recording from 'react-native-recording'
import filterSentenceForAnalysis, {checkName, getNormalPhone} from '../../helpers/contentForIbm'
import {connect} from 'react-redux'
import styles from '../../config/styles'
var Sound = require('react-native-sound')

class SelfLearningShow extends Component {
    static navigationOptions = ({ navigation }) => {
        return {
            title: '练习模式',
            headerRight: <View />
        }
    }

    constructor(props) {
        super(props)
        this.state = {
            id: props.navigation.state.params.id,
            loading: true,
            sentences: [],
            active_sentence_id: null,
            playing: false,
            recording: false,
            playbacking: false,
            ws: null,
            wsLocked: false,
            recordingSeconds:0
        }
    }

    componentDidMount () {
        this.getData()
        this.listener = Recording.addRecordingEventListener((data) => {
            if (this.state.ws != null && this.state.ws.readyState === 1) {
                this.state.ws.send(JSON.stringify({
                    stream_type: 'array',
                    stream: data,
                    status: 'process'
                }))
            }
        })
    }

    componentWillUnmount() {
        // Recording.stop()
        if(this.timer) clearInterval(this.timer);
        Sound.setCategory('Playback')
        this.listener.remove()
    }

    getData = () => {
        GetChapterApi(this.state.id).then((data) => {
            if (data.code == 0) {
                this.setState({
                    sentences: data.sentences,
                    loading: false,
                    active_sentence_id: data.sentences[0].id
                })
            }
        })
    }

    /*
        以下几个方法用来控制所有sentence，任何正在
        播放，录音，回放的sentence都会使其他组件
        无法执行操作，所以通过父组件来控制全局的状态
     */

    //设置当前选中的Sentence
    setActiveSentenceId = (sentence_id) => {
        this.setState({active_sentence_id: sentence_id})
    }

    //设置是否在播放
    setPlayState = (state) => {
        this.setState({playing: state})
    }

    //设置是否在录音
    setRecordingState = (state) => {
        this.setState({recording: state})
    }

    //设置是否在回放
    setPlaybackState = (state) => {
        this.setState({playbacking: state})
    }

    getSeconds = () => {
        return this.state.recordingSeconds;
    }

    onRecordingButtonPress = (sentence, timeStamp) => {
        return new Promise((resolve, reject) => {
            const {playing, recording, playbacking} = this.state
            const {user} = this.props.user

            if (playing || playbacking) return
            Sound.setCategory('Record')
            if (recording) {
                Recording.stop()
                //this.listener.remove()
                this.setRecordingState(false)
                //end
                if (this.state.ws != null && this.state.ws.readyState === 1) {
                    this.state.ws.send(JSON.stringify({
                        status: 'end'
                    }))
                }
                clearInterval(this.timer);
            } else {
                //start record
                if (this.state.wsLocked) {
                    this.setRecordingState(false)
                    return
                }

                //一次点击后，锁定，不能连续点击
                this.state.wsLocked = true
                setTimeout(() => {this.state.wsLocked = false}, 150)
                this.setRecordingState(true)
                const {user} = this.props.user
                let _content = filterSentenceForAnalysis(sentence.content, sentence.grouped_content)
                this.state.ws = new WebSocket(
                    `ws://${user.login_name}:${timeStamp}@54.223.255.113:8008?` +
                    `content=${encodeURI(_content)}&id=${user.login_name}&timestamp=${timeStamp}&buffer_size=8192`
                )

                //连接上了才开始录音
                this.state.ws.onopen = (e) => {
                    this.setState({
                        recordingSeconds:0
                    })
                    this.timer = setInterval(() => {
                        this.state.recordingSeconds++;
                    }, 1000)
                    Recording.init({bufferSize: 8192,sampleRate: 16000})
                    Recording.start()
                }

                this.state.onerror = (e) => {
                    try {
                        this.state.ws.close()
                        this.state.ws = null
                    } catch (e) {
                        reject(e)
                    }
                }
                
                this.state.ws.onmessage = (e) => {
                    resolve([e,this.getSeconds]);
                    // 接收到了一个消息
                    if (this.state.ws != null && this.state.ws.readyState === 1) {
                        this.state.ws.close()
                        this.state.ws = null
                    }
                    
                };

            
            }
        })
        
    }

    //开始挑战
    startChallenge = () => {
        const {navigation} = this.props
        Recording.stop()
        //this.listener.remove()

        //下面的这段代码用来解决React Native安卓的一个官方bug, 暂时先这样解决一下，等官方回复
        //======================================
        // let _sentences = this.state.sentences
        // this.setState({sentences: []}, () => {
        //     setTimeout(this.setState({
        //         sentences: _sentences
        //     }), 100)
        // })
        //======================================
        navigation.navigate('challenge', {sentences: this.state.sentences})
    }

   
    render () {
        if (this.state.loading == true) {
            return <Loading />
        } else {
            return(
                <View style={{flex: 1}}>
                     <ScrollView style={{flex: 1}}>
                        {
                            this.state.sentences.map((sentence, index) => {
                                return (
                                    <SentenceLabel
                                        sentence={sentence}
                                        isActive={this.state.active_sentence_id == sentence.id}
                                        isPlaying={this.state.playing}
                                        isRecording={this.state.recording}
                                        isPlaybacking={this.state.playbacking}
                                        key={index}
                                        onPress={this.setActiveSentenceId}
                                        setPlayState={this.setPlayState}
                                        setRecordingState={this.setRecordingState}
                                        setPlaybackState={this.setPlaybackState}
                                        onRecordingButtonPress={this.onRecordingButtonPress}

                                        //onRecording={this.onRecording}
                                    />  
                                )
                            })
                        }
                    
                    </ScrollView>
                    <View style={{ justifyContent: 'center', alignItems: 'center'}}>
                        <TouchableOpacity
                            style={[styles.begin_challenge, {alignItems: 'center'}]}
                            onPress={this.startChallenge}
                            activeOpacity={0.2}
                            focusedOpacity={0.5}>
                            <Text style={{color:'#ffffff'}}>开始挑战</Text>
                        </TouchableOpacity>
                    </View>
                  
                </View>
               
            )  
        }  
    }
}


const mapStateToProps = (state) => {
    return {
       user: state.user
    }
}

export default connect(mapStateToProps)(SelfLearningShow)